<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

/**
 * goBack()
 *
 * @return
 */
if ( ! function_exists('goBack'))
{
	function goBack()
	{
	    $CI =& get_instance();
        if ($CI->agent->is_referral()) {
            $referer_url = $CI->agent->referrer();
            redirect($referer_url);
        }
	}
}

/**
 * url_concat()
 *
 * @return
 */
if ( ! function_exists('url_concat'))
{
	function url_concat()
	{
        $url='';
        $arg_list = func_get_args();
        if(!empty($arg_list)){
            for ($i = 0; $i < count($arg_list); $i++) {
                 $url= $url.trim_slashes($arg_list[$i])."/";
            }
        }
        $url = substr($url,0,-1);
        return $url;
	}
}

/**
 * getVNDateTime()
 *
 * @return
 */
if ( ! function_exists('getVNDateTime'))
{
	function getVNDateTime($datetime,$config=array(),$gio=false)
	{
		$date = '';
		$format = '';
		if(!empty($datetime)){
			$show_date = isset($config['show_date']) ? $config['show_date'] : true;
			$show_time = isset($config['show_time']) ? $config['show_time'] : true;
			$show_time_second = isset($config['show_time_second']) ? $config['show_time_second'] : true;
			if($show_date){
				$date_format = 'd-m-Y';
				$format = $date_format;
			}
			if($show_time){
				$time_format = 'H:i';
				if($show_time_second){
					$time_format .= ':s';
				}
				$format = !empty($format) ? $format.' ': $format;
				$format .= $time_format;
			}
			$date = date($format, strtotime($datetime));
		}
		return $date;
	}
}

/**
 * getNow()
 *
 * @return
 */
if ( ! function_exists('getNow'))
{
	function getNow()
	{
		return date(DATETIME_FORMAT_DB);
	}
	
	function getToday($day_adding=0)
	{
		$today = date(DATETIME_FORMAT_DB_NO_TIME);  //Lay ngay hien tai
		$today = strtotime($today);   // chuyen chuyen thanh thoi gian
		$result = $today + $day_adding*3600*24; 
		$result = date(DATETIME_FORMAT_DB,$result);
		return $result;
	}
}

if ( ! function_exists('getmicrotime'))
{
	// a function to  get microtime
	function getmicrotime(){
		list($usec, $sec) = explode(" ",microtime());
		return ((float)$usec + (float)$sec);
	}
}

/****************************	BEGIN: JSON HELPER ***************************/
if ( ! function_exists('json_encode'))
{
	function json_encode($id_str)
	{
		
	}
}
/****************************	END: JSON HELPER ***************************/

/****************************	BEGIN: DATABASE HELPER ***************************/
if ( ! function_exists('generate_in_query'))
{
	function generate_in_query($id_str)
	{
		$in_query = '';
		if(!empty($id_str)){
			$ids = split(',',$id_str);
			if(!empty($ids)){
				foreach($ids as $id){
					if(!empty($id)){
						$id = (int)$id;
						$in_query .= $id.',';
					}
				}
				$in_query = substr($in_query,0,-1);
			}
		}
		return $in_query;
	}
}
/****************************	END: DATABASE HELPER ***************************/

/****************************	BEGIN: FILE HELPER ***************************/
if ( ! function_exists('get_extension'))
{
	function get_extension($file_name)
	{
		return substr(strrchr($file_name,'.'),1);
	}
}

if ( ! function_exists('get_file_extension'))
{
	function get_file_extension($file_path, &$file_name=null){
		$extension = '';
		if(!empty($file_path)){
			$parts = pathinfo($file_path);
			if(!empty($parts['extension'])){
				$extension  = $parts['extension'];
				if($file_name !== null){
					$file_name = $parts['filename'];
				}
			}
		}
		return $extension;
	}
}

if ( ! function_exists('check_exists_create'))
{
	function check_exists_create($dir_name, &$file_name, &$extension='')
	{
		$parts = pathinfo($file_name);
		$extension  = $parts ['extension'];
		$file_name = basename($file_name,".$extension");
		// Should be 9 cases
		$is_existed = 	file_exists($dir_name.$file_name.".$extension") || 
					file_exists($dir_name.$file_name.strtolower(".$extension")) ||
					file_exists($dir_name.$file_name.strtoupper(".$extension"));
		if($is_existed){
			$suffix = date(DATETIME_FORMAT_HYPHEN);
			$file_name = $file_name."_".$suffix;
		}
		$file_name  = "$file_name.$extension";
		return $is_existed;
	}
}

if ( ! function_exists('check_exists_dir'))
{
	function check_exists_dir($dir_name)
	{
		if(!file_exists($dir_name)) 
		{ 
			$recursive = true;
			$old_umask = umask(0);
			mkdir($dir_name,0777,$recursive);
			umask($old_umask);
		} 
	}
}

/**
 * Delete a file or recursively delete a directory
 *
 * @param string $str Path to file or directory
 */
function recursiveDelete($str){
	if(is_file($str)){
		return @unlink($str);
	}
	elseif(is_dir($str)){
		$scan = glob(rtrim($str,'/').'/*');
		foreach($scan as $index=>$path){
			recursiveDelete($path);
		}
		return @rmdir($str);
	}
}

if ( ! function_exists('get_dirname_by_ext'))
{
	function get_dirname_by_ext($file_name)
	{
		$dirname = UPLOAD_DIR;
		$parts = pathinfo($file_name);
		$extension  = strtolower($parts['extension']);
		switch($extension){
			case 'flv':
				$dirname = VIDEO_DIR;
				break;
			case 'mp3':
				$dirname = AUDIO_DIR;
				break;
			case 'doc':
			case 'docx':
			case 'xls':
			case 'xlsx':
			case 'ppt':
			case 'pptx':
			case 'pdf':
				$dirname = DOCUMENT_DIR;
				break;
			case 'rar':
			case 'zip':
				$dirname = ZIP_DIR;
				break;
			case 'jpg':
			case 'png':
			case 'gif':
				$dirname = IMAGE_THUMBNAIL_88X66;
				break;
		}
		return $dirname;
	}
}

if ( ! function_exists('get_extension'))
{
	function get_extension($file_name)
	{
		$parts = pathinfo($file_name);
		$extension  = strtolower($parts['extension']);
		return $extension;
	}
}

if ( ! function_exists('get_icon'))
{
	function get_icon($file_name)
	{
		$icon = "";
		$parts = pathinfo($file_name);
		$extension = "";
		if(!empty($parts['extension'])){
			$extension  = strtolower($parts['extension']);
		}
		switch($extension){
			case 'doc':
			case 'docx':
				$icon = "DOC-48.png";
				break;
			case 'xls':
			case 'xlsx':
				$icon = "EXL-48.png";
				break;
			case 'img':
				$icon = "IMG-48.png";
				break;
			case 'mp3':
				$icon = "MP3-48.png";
				break;
			case 'flv':
				$icon = "FLV-48.png";
				break;
			case 'pdf':
				$icon = "PDF-48.png";
				break;
			case 'ppt':
			case 'pptx':
				$icon = "PPT-48.png";
				break;
			case 'rar':
			case 'zip':
				$icon = "ZIP-48.png";
				break;
			default:
				$icon = "other-48.png";
				break;
		}
		return $icon;
	}
}

if ( ! function_exists('check_empty_folder'))
{
	function check_empty_folder($folder )
	{
		$files = array ();
		if ( $handle = opendir ( $folder ) ) {
			while ( false !== ( $file = readdir ( $handle ) ) ) {
				if ( $file != "." && $file != ".." ) {
					$files [] = $file;
				}
			}
			closedir ( $handle );
		}
		return ( count ( $files ) > 0 ) ? FALSE : TRUE;
	}
}

if ( ! function_exists('recurse_copy'))
{
	function recurse_copy($src,$dst) {
		$dir = opendir($src);
		@mkdir($dst);
		while(false !== ( $file = readdir($dir)) ) {
			if (( $file != '.' ) && ( $file != '..' )) {
				if ( is_dir($src . '/' . $file) ) {
					recurse_copy($src . '/' . $file,$dst . '/' . $file);
				}
				else {
					copy($src . '/' . $file,$dst . '/' . $file);
				}
			}
		}
		closedir($dir);
	} 
}
/****************************	END: FILE HELPER ***************************/

/****************************	BEGIN: DEBUG HELPER ***************************/
if ( ! function_exists('last_query'))
{
	function last_query($exit=false)
	{
		$CI =& get_instance();
		echo $CI ->db->last_query();
		if($exit){
			exit();
		}
	}
}

if ( ! function_exists('pr'))
{
	function pr($item, $exit=false)
	{
		$output = '';
		
		ob_start();
		echo "<pre/>";
		if(is_array($item) || is_object($item)){
			var_dump($item);
		} else {
			echo $item;
		}
		$output = ob_get_contents();
		ob_end_clean();
		
		echo $output;
		
		if($exit){
			exit();
		}
		return $output;
	}
}

if ( ! function_exists('var_dump_ret'))
{
	function var_dump_ret($mixed = null) {
	  ob_start();
	  var_dump($mixed);
	  $content = ob_get_contents();
	  ob_end_clean();
	  return $content;
	}
}
/****************************	END: DEBUG HELPER ***************************/


/****************************	BEGIN: URL HELPER ***************************/
if ( ! function_exists('full_url'))
{
	function full_url()
	{
		$query = $_SERVER['QUERY_STRING'] ? '?'.$_SERVER['QUERY_STRING'] : '';
		$full_url = substr(base_url(),0,-1).uri_string(). $query; 
		return $full_url;
	}
}

if ( ! function_exists('process_url'))
{
	function process_url($url){
		if(!$url)
			return '';
		$http_post = strpos($url,'http://') === false ? strpos($url, 'https://') : strpos($url, 'http://');	
		if($http_post !== false)
				return $url;
		return 'http://'. $url;
	}
}
/****************************	END: URL HELPER ***************************/

/****************************	BEGIN: IMAGE HELPER ***************************/
if ( ! function_exists('resize_image'))
{
	function resize_image($source_dir, $file_name, $width, $height, $des_dir)
	{
		require_once 'phpthumb/ThumbLib.inc.php';  
		$thumb = PhpThumbFactory::create($source_dir.$file_name);  
		$thumb->resize($width, $height);
		$thumb->save($des_dir.$file_name);
	}
}

if ( ! function_exists('resize_image_simple'))
{
	function resize_image_simple($source, $width, $height, $des)
	{
		require_once 'phpthumb/ThumbLib.inc.php';  
		$thumb = PhpThumbFactory::create($source);  
		$thumb->resize($width, $height);
		$thumb->save($des);
		return getImageResource($des);
	}
}

if ( ! function_exists('crop_image'))
{
	function crop_image($dataUpload, $src, $width_o, $height_o, $des, $noCheckImgage=false, $is_white_background=true)
	{
		log_message('error', 'dataUpload: '.var_dump_ret($_FILES));
		if($noCheckImgage || $dataUpload['is_image'] == true)
		{
			// Get the image and create a thumbnail
			$ham = "imagecreatefrom".$dataUpload['image_type'];
			log_message('error', 'Begin ham');
			$img = $ham($src);
			if (!$img) {
				log_message("ERROR:could not create image handle ". $_FILES["Filedata"]["tmp_name"]);
				exit(0);
			}
			$width = imageSX($img);
			$height = imageSY($img);
			if (!$width || !$height) {
				echo "ERROR:Invalid width or height";
				exit(0);
			}
			// Build the thumbnail
			$target_width = $width_o;
			$target_height = $height_o;
			$target_ratio = $target_width / $target_height;
			$img_ratio = $width / $height;
			if ($target_ratio - $img_ratio > 0.001) {
				$new_height = $target_height;
				$new_width = $img_ratio * $target_height;
			} else {
				$new_height = $target_width / $img_ratio;
				$new_width = $target_width;
			}
			if ($new_height > $target_height) {
				$new_height = $target_height;
			}
			if ($new_width > $target_width) {
				$new_height = $target_width;
			}
			
			if(!$is_white_background){
				// Copy
				copy($src,$des);
				
				// Resize copied image
				$tmpname = $des;
				$save_dir = '';
				$dir = '';
				$ah = $new_height;
				$aw = $new_width;
				img_resize($tmpname,$save_dir,$ah,$aw,$dir);
			} else {
				$new_img = ImageCreateTrueColor($width_o, $height_o);
				$white = imagecolorallocate($new_img, 255, 255, 255);
				if (!@imagefilledrectangle($new_img, 0, 0, $target_width-1, $target_height-1, $white)) {	// Fill the image black
					echo "ERROR:Could not fill new image";
					exit(0);
				}
				if (!@imagecopyresampled($new_img, $img, ($target_width-$new_width)/2, ($target_height-$new_height)/2, 0, 0, $new_width, $new_height, $width, $height)) {
					echo "ERROR:Could not resize image";
					exit(0);
				}
				if (!isset($_SESSION["file_info"])) {
					$_SESSION["file_info"] = array();
				}
				// Use a output buffering to load the image into a variable
				$ham = "image".$dataUpload['image_type'];
				if($ham == 'imagejpeg'){
					$ham($new_img, $des, 100);
				} else if($ham == 'imagepng'){
					$ham($new_img, $des, 9);
					imageAlphaBlending($new_img, true);
					imageSaveAlpha($new_img, true);
				} else {
					$ham($new_img, $des,100);
				}
				// Get the image and create a thumbnail
			}
		}
	}
}

if ( ! function_exists('img_resize'))
{
	function img_resize( $tmpname,$save_dir,$ah,$aw,$dir) {
		//$save_dir .= ( substr($save_dir,-1) != "/") ? "/" : "";
		$gis = getimagesize($save_dir.$tmpname);
		$type = $gis[2];
		switch($type) {
		case "1": $imorig = imagecreatefromgif($save_dir.$tmpname); break;
		case "2": $imorig = imagecreatefromjpeg($save_dir.$tmpname);break;
		case "3": $imorig = imagecreatefrompng($save_dir.$tmpname); break;
		default: $imorig = imagecreatefromjpeg($save_dir.$tmpname);
		}
		$x = imagesx($imorig);
		$y = imagesy($imorig);
		if($ah=='auto' && is_numeric($aw)){
			$ah=($aw/$x*100)*($y/100);
		}
		if($aw=='auto' && is_numeric($ah)){
			$aw=($ah/$y*100)*($x/100);
		}
		$im = imagecreatetruecolor($aw,$ah);
		
		if($type == 3){ // PNG
			//preserve alpha (transparency)
			// http://php.net/manual/en/function.imagecopyresampled.php
			imagecolortransparent($im, imagecolorallocate($im, 0, 0, 0));
			imagealphablending($im, false);
			imagesavealpha($im, true);
			if (imagecopyresampled($im,$imorig , 0,0,0,0,$aw,$ah,$x,$y)) {
				imagepng($im, $save_dir.$dir.$tmpname,9);
			}			
		} else {
			if (imagecopyresampled($im,$imorig , 0,0,0,0,$aw,$ah,$x,$y)) {
				imagejpeg($im, $save_dir.$dir.$tmpname,100);
			}
		}
	}
}

if ( ! function_exists('resize_transparent'))
{
	function resize_transparent($src,$des_width,$des_height,$des)
	{
		$src_size = getimagesize($src);
		$src_width = $src_size[0];
		$src_height = $src_size[1];
		$is_resized = false;
		$resized_width = 0;
		$resized_height = 0;
		if($src_width > $des_width){
			$is_resized = true;
			$resized_width = $des_width;
			$resized_height = $des_width/$src_width*$src_height;
		} else if($src_height > $des_height){
			$is_resized = true;
			$resized_height = $des_height;
			$resized_width = $des_height/$src_height*$src_width;
		} else {
			$is_resized = true;
			$resized_width = $src_width;
			$resized_height = $src_height;
		}
		
		if($is_resized){
			// Transparent background
			$resized_transparent = TRANSPARENT_RESIZE_DIR.uniqid().'.png';
			$resized_transparent_resource = resize_image_simple(TRANSPARENT_FILE_PATH,$des_width,$des_height,$resized_transparent);
			
			//Image
			$resized_temp_image = IMAGE_THUMBNAIL_DIR.uniqid().'.'.get_file_extension($src);
			$resized_temp_image_resource = resize_image_simple($src, $resized_width, $resized_height, $resized_temp_image);

			//Copy
			$dest_x = ($des_width - $resized_width)/2;
			$dest_y = ($des_height - $resized_height)/2;
			imagecopy($resized_transparent_resource, $resized_temp_image_resource, $dest_x, $dest_y, 0, 0, $resized_width, $resized_height);
			// Make transparency background
			imagealphablending($resized_transparent_resource, false);
			imagesavealpha($resized_transparent_resource, true);
			imagepng($resized_transparent_resource, $des);
			imagedestroy($resized_transparent_resource);
			imagedestroy($resized_temp_image_resource);
			unlink($resized_transparent);
			unlink($resized_temp_image);
		}
	}
}

if ( ! function_exists('autobay_watermark'))
{
	function autobay_watermark($image_file_path, $watermark)
	{
		$watermark_size = getimagesize($watermark);
		// Standard size
		// Image size: 700x525
		// Watermark size: 200x50
		$margin_width = 56;
		$margin_height = 44;
		$margin_width_center =  180;
		$margin_height_center =  345;
		if(!empty($watermark_size)){
			$watermark_width = $watermark_size[0];
			$watermark_height = $watermark_size[1];
		} else {
			return;
		}
		
		$min_image_width = ($watermark_width+$margin_width)*2+$margin_width_center;
		$min_image_height = ($watermark_height+$margin_height)*2+$margin_height_center;
			
		$image_size = getimagesize($image_file_path);
		if(!empty($image_size)){
			$image_width = (int)$image_size[0];
			$image_height = (int)$image_size[1];
			
			if($image_width < $min_image_width || $image_height < $min_image_height){
				if($image_width < $image_height){
					$portion = $image_width/$min_image_width;
				} else {
					$portion = $image_height/$min_image_height;
				}
				/*$watermark_width = $portion*$watermark_width;
				$watermark_height = $portion*$watermark_height;*/
				$watermark_width = $watermark_width;
				$watermark_height = $watermark_height;
				$margin_width = $portion*$margin_width;
				$margin_height = $portion*$margin_height;
				$resized_watermark = WATERMARK_RESIZE_DIR.uniqid().'.'.get_file_extension($watermark);
				resize_image_simple($watermark,$watermark_width,$watermark_height,$resized_watermark);
				$watermark = $resized_watermark;
			}
			$x1 = $margin_width;
			$x2 = $image_width - $watermark_width - $margin_width;
			$y1 = $margin_height;
			$y2 = $image_height - $watermark_height - $margin_height;
            $x3 = ($image_width - $watermark_width)/2;
            $y3 = ($image_height - $watermark_height)/2;
			/*watermark($image_file_path, $watermark, 0, 0);
            watermark($image_file_path, $watermark, $x2, $y1);
            watermark($image_file_path, $watermark, $x1, $y2);
            watermark($image_file_path, $watermark, $x2, $y2);*/
            watermark($image_file_path, $watermark, $x3, $y3);
			if(!empty($resized_watermark)){
				unlink($resized_watermark);
			}
		} else {
			return;
		}
	}
}

if ( ! function_exists('watermark'))
{
	function watermark($image_file_path, $watermark, $dest_x=0, $dest_y=0)
	{
		require_once 'phpthumb/ThumbLib.inc.php';
		$thumb = PhpThumbFactory::create($image_file_path);
		$thumb->createWatermark($watermark, $dest_x, $dest_y);
        
		$thumb->save($image_file_path);
	}
}

if ( ! function_exists('getImageResource'))
{
	function getImageResource($image_file_path)
	{
		$pathinfo = pathinfo($image_file_path);
		$var1 = $pathinfo['extension'];
		$var2 = "png";
		$var3 = "jpeg";
		$var4 = "jpg";
		$var5 = "gif";
		if(strcasecmp($var1, $var2) == 0){
			$image_file_path = @imagecreatefrompng($image_file_path);
		}elseif((strcasecmp($var1, $var3) == 0) || (strcasecmp($var1, $var4) == 0)){
			$image_file_path = @imagecreatefromjpeg($image_file_path);
		}elseif(strcasecmp($var1, $var5) == 0){
			$image_file_path = @imagecreatefromgif($image_file_path);
		}
		return $image_file_path;
	}
}

if ( ! function_exists('getImageType'))
{
	function getImageType($file_name)
	{
	    $extension = get_extension($file_name);
	    $extension = strtolower($extension);
        if($extension == 'jpg'){
            $extension = 'jpeg';
        }
        return $extension;
    }
 }
/****************************	END: IMAGE HELPER ***************************/

/****************************	BEGIN: PAGINATION HELPER ***************************/
function paginate($ci_instance, $base_url, $total_rows = 100, $current_page = 1, $per_page=10, $action = '', $suffix=''){
    if($ci_instance != null){
    	$ci_instance->load->library('pagination');
    	$config['cur_page'] = $current_page;					
    	$config['base_url'] = $base_url;
    	$config['total_rows'] = $total_rows;
    	$config['per_page'] = $per_page;
    	$config['page_query_string'] = false;
    	$config['uri_segment'] = 100;
    	$config['next_link'] = '<img src="'.base_url().'images/p_next.gif" align="absmiddle" />';
        //$config['next_link'] = '';
        $config['next_tag_open'] = '<div class="next_link">';
        $config['next_tag_close'] = '</div>';
        $config['prev_link'] = '<img src="'.base_url().'images/p_prev.gif" align="absmiddle" />';
        //$config['prev_link'] = '';
    	$config['prev_tag_open'] = '<div class="prev_link">';
        $config['prev_tag_close'] = '</div>';
    	$config['cur_tag_open'] = '<b class="green">';
    	$config['cur_tag_close'] = '</b>';
        $config['full_tag_open'] = '<div class="paginator_number" style="width:auto;">';
        $config['full_tag_close'] = '<div class="clearBoth"></div></div>';
        $config['num_links'] = 4;
        $config['num_tag_open'] = '<div>';
        $config['num_tag_close'] = '</div>';
        
        $config['first_link'] = '';
        $config['first_tag_open'] = '<div class="first_link">';
        $config['first_tag_close'] = '</div>';
        
        $config['last_link'] = '';
        $config['last_tag_open'] = '<div class="last_link">';
        $config['last_tag_close'] = '</div>';
    	
    	$ci_instance->pagination->initialize($config);	
    	$paginator = $ci_instance->pagination->create_links(false,true);

    	if(!empty($action) && !empty($suffix)){
            if($action == SEARCH_URL_LINK){
				// Fix first link
				$paginator = str_replace('tim-kiem/trang/"','tim-kiem/"',$paginator);
				
				// From: 	http://localhost/autobay/Code/mua-ban-oto/tu-khoa/acura+mdx+2007+2010+ho+chi+minh/tim-kiem/trang/15
				// To: 		http://localhost/autobay/Code/mua-ban-oto/tu-khoa/acura+mdx+2007+2010+ho+chi+minh/trang/15/tim-kiem
				$pattern = '/\/tim-kiem\/trang\/(\d+)/'; // $pattern = '/(.*)\/tim-kiem\/(\d+)/'; // -> Wrong???
                $replacement = '/trang/$1/tim-kiem';
            } else if($action == 'detail'){
                $pattern = '/'.$action.'(\/\d*)(\/\d*)(\/\d*)/';
                $replacement = $action.'$1$2$3?'.$suffix;
            } else if($action == 'chitiet_nv_kinh_doanh'){
                $pattern = '/'.$action.'(\/\d*)(\/\d*)(\/\d*)/';
                $replacement = $action.'$1$2$3?'.$suffix;
            }
			$paginator = preg_replace($pattern, $replacement, $paginator);
    	}
		$data['paginator'] = $paginator;
        $ci_instance->load->vars($data);
    }
}

function paginate_new($ci_instance, $base_url, $total_rows = 100, $current_page = 1, $per_page=10, $action = '', $suffix='', $num_links=4){
    if($ci_instance != null){
		if($per_page == -1){
			$per_page = $total_rows;
		}
    	$ci_instance->load->library('pagination');
		
    	$config['cur_page'] = $current_page;					
    	$config['base_url'] = $base_url;
    	$config['total_rows'] = $total_rows;
    	$config['per_page'] = $per_page;
    	$config['page_query_string'] = false;
    	$config['uri_segment'] = 100;
    	$config['next_link'] = '<img src="'.base_url().'images/p_next.gif" align="absmiddle" />';
        //$config['next_link'] = '';
        $config['next_tag_open'] = '<div class="next_link">';
        $config['next_tag_close'] = '</div>';
        $config['prev_link'] = '<img src="'.base_url().'images/p_prev.gif" align="absmiddle" />';
        //$config['prev_link'] = '';
    	$config['prev_tag_open'] = '<div class="prev_link">';
        $config['prev_tag_close'] = '</div>';
    	$config['cur_tag_open'] = '<div class="green">';
    	$config['cur_tag_close'] = '</div>';
        $config['full_tag_open'] = '<div class="paginator_number" style="width:auto;">';
        $config['full_tag_close'] = '</div>';
        $config['num_links'] = $num_links;
        $config['num_tag_open'] = '<div class="white">';
        $config['num_tag_close'] = '</div>';
        
        $config['first_link'] = '';
        $config['first_tag_open'] = '<div class="first_link">';
        $config['first_tag_close'] = '</div>';
        
        $config['last_link'] = '';
        $config['last_tag_open'] = '<div class="last_link">';
        $config['last_tag_close'] = '</div>';
    	
    	$ci_instance->pagination->initialize($config);
    			
    	$data['paginator'] = $ci_instance->pagination->create_links(false,true);
    	if(!empty($action) && !empty($suffix)){
            if($action == 'search_result'){
                $pattern = '/'.$action.'(\/?)(\d*)/';
                $replacement = $action.'$1$2?'.$suffix;
            } else if($action == 'detail'){
                $pattern = '/'.$action.'(\/\d*)(\/\d*)(\/\d*)/';
                $replacement = $action.'$1$2$3?'.$suffix;
            } else if($action == 'query_format'){
                $pattern = '/'.$suffix.'=(\/)(\d*)/';
                $replacement = $suffix.'=$2';
            }
			$data['paginator'] = preg_replace($pattern, $replacement, $data['paginator']);
    	}
        $ci_instance->load->vars($data);
    }
}
/****************************	END: PAGINATION HELPER ***************************/

/****************************	BEGIN: QUERY HELPER ***************************/
if ( ! function_exists('cond_and'))
{
	function cond_and(&$query, $condition)
	{
		if(empty($query)){
			$query = $condition;
		} else {
			$query = "$query AND $condition";
		}
	}
}
/****************************	END: QUERY HELPER ***************************/


/****************************	BEGIN: INTERNET HELPER ***************************/
if ( ! function_exists('getIP')){
	function getIP(){
		if (!empty($_SERVER['HTTP_CLIENT_IP']))  //check ip from share internet
		{
		  $ip=$_SERVER['HTTP_CLIENT_IP'];
		}
		elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   
		//to check ip is pass from proxy
		{
		  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
		}
		else
		{
		  $ip=$_SERVER['REMOTE_ADDR'];
		}
		return $ip;
	}
}
/****************************	END: INTERNET HELPER ***************************/

/****************************	BEGIN: TEXT HELPER ***************************/
function bo_dau($cs){
    $marTViet=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă",
	"ằ","ắ","ặ","ẳ","ẵ","è","é","ẹ","ẻ","ẽ","ê","ề"
	,"ế","ệ","ể","ễ",
	"ì","í","ị","ỉ","ĩ",
	"ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
	,"ờ","ớ","ợ","ở","ỡ",
	"ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
	"ỳ","ý","ỵ","ỷ","ỹ",
	"đ",
	"À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
	,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
	"È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
	"Ì","Í","Ị","Ỉ","Ĩ",
	"Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
	,"Ờ","Ớ","Ợ","Ở","Ỡ",
	"Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
	"Ỳ","Ý","Ỵ","Ỷ","Ỹ",
	"Đ");

	$marKoDau=array("a","a","a","a","a","a","a","a","a","a","a"
	,"a","a","a","a","a","a",
	"e","e","e","e","e","e","e","e","e","e","e",
	"i","i","i","i","i",
	"o","o","o","o","o","o","o","o","o","o","o","o"
	,"o","o","o","o","o",
	"u","u","u","u","u","u","u","u","u","u","u",
	"y","y","y","y","y",
	"d",
	"A","A","A","A","A","A","A","A","A","A","A","A"
	,"A","A","A","A","A",
	"E","E","E","E","E","E","E","E","E","E","E",
	"I","I","I","I","I",
	"O","O","O","O","O","O","O","O","O","O","O","O"
	,"O","O","O","O","O",
	"U","U","U","U","U","U","U","U","U","U","U",
	"Y","Y","Y","Y","Y",
	"D");
	return str_replace($marTViet,$marKoDau,$cs);
}

if ( ! function_exists('html2text'))
{
	function html2text($html)
	{
		// Include the class definition file.
		require_once('class.html2text.php');

		// Instantiate a new instance of the class. Passing the string
		// variable automatically loads the HTML for you.
		$h2t =& new html2text($html);

		// Simply call the get_text() method for the class to convert
		// the HTML to the plain text. Store it into the variable.
		return $h2t->get_text();
	}
}
/****************************	END: TEXT HELPER ***************************/